package com.xdqzy.baseline.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdqzy.baseline.common.annotation.CacheDelete;
import com.xdqzy.baseline.common.annotation.CacheParam;
import com.xdqzy.baseline.common.annotation.Combine;
import com.xdqzy.baseline.common.exception.CtbcAssert;
import com.xdqzy.baseline.common.manager.RedisCacheManager;
import com.xdqzy.baseline.demo.constant.ProductConstants;
import com.xdqzy.baseline.demo.controller.param.req.AddProductReq;
import com.xdqzy.baseline.demo.controller.param.resp.ProductDemoResp;
import com.xdqzy.baseline.demo.mapper.ProductDemoMapper;
import com.xdqzy.baseline.demo.model.ProductDemoModel;
import com.xdqzy.baseline.demo.service.ProductDemoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author qss
 * @since 2020-11-15
 */
@Service
public class ProductDemoServiceImpl extends ServiceImpl<ProductDemoMapper, ProductDemoModel> implements ProductDemoService {

    @Resource
    private RedisCacheManager redisCacheManager;


    @PostConstruct
    public void init() {
        //注入缓存管理
        redisCacheManager.registerLoader(ProductConstants.PRODUCT_CACHE, "product:id:", this::listByIds);
    }

    /**
     * 根据id获取商品
     *
     * @param id
     * @return
     */
    //注解聚合数据
    @Combine(ProductDemoResp.class)
    @Override
    public ProductDemoResp getProduct(String id) {
        ProductDemoModel demoModel = getById(id);
        CtbcAssert.isTrue(demoModel != null, "商品不存在");
        ProductDemoResp resp = new ProductDemoResp();
        BeanUtils.copyProperties(demoModel, resp);
        return resp;
    }

    @Combine(ProductDemoResp.class)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ProductDemoResp addProduct(AddProductReq addProductReq) {
        ProductDemoModel model=new ProductDemoModel();
        BeanUtils.copyProperties(addProductReq,model);
        model.setCreateTime(new Date());
        boolean save = save(model);
        CtbcAssert.isTrue(save,"保存失败");
        ProductDemoResp resp = new ProductDemoResp();
        BeanUtils.copyProperties(model, resp);
        return resp;
    }

    /**
     * 删除商品同时删除缓存
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheDelete(ProductConstants.PRODUCT_CACHE)
    @Override
    public void deleteById(@CacheParam String id) {
        boolean remove = removeById(id);
        CtbcAssert.isTrue(remove,"删除失败");

    }
}
